using System.Security.Cryptography;
using System.Text;

namespace ClassDemo.Services;

/// <summary>
/// 密码服务实现
/// </summary>
public class PasswordService : IPasswordService
{
    /// <summary>
    /// 加密密码
    /// </summary>
    /// <param name="password">原始密码</param>
    /// <returns>加密后的密码</returns>
    public string HashPassword(string password)
    {
        if (string.IsNullOrEmpty(password))
            throw new ArgumentException("密码不能为空", nameof(password));

        // 使用SHA256加密
        using var sha256 = SHA256.Create();
        var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
        return Convert.ToBase64String(hashedBytes);
    }

    /// <summary>
    /// 验证密码
    /// </summary>
    /// <param name="password">原始密码</param>
    /// <param name="hashedPassword">加密后的密码</param>
    /// <returns>是否匹配</returns>
    public bool VerifyPassword(string password, string hashedPassword)
    {
        if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(hashedPassword))
            return false;

        var hashOfInput = HashPassword(password);
        return hashOfInput.Equals(hashedPassword, StringComparison.OrdinalIgnoreCase);
    }
}